//const OpenAI = require("openai");

const queryAI = async (code,analysisType) => {
    var content =""
    if (analysisType =="代码结构分析")
        content ="请从类名建议、命名建议、命名与内容的关联性、代码的内联性进行分析。在内联性方面，要检测这个代码是否包含了多个不同维度的功能。 不需要深度思考过程,限定在300字内。";
    if (analysisType == "知识图谱分析") {
        content = "请分析上述代码的实体、关系，并构建一个可以在公开网站上显示的知识图谱的JSON格式。你只需要返回JSON即可，不需要别的内容。" +
            "其中json的格式{'entities':[]},每个实体包括name,attributes,relationships。其中relationships是一个数组，包括type、target."
    }
    if (analysisType=="代码质量打分")
        content = "请从命名规则、内容相关性、代码整洁度、关联性等方面给下面代码进行综合打分，总分100。只需要返回最后分数，不需要解释.";

    content = content+"下面是具体代码" + code;
    
    return byHttp(content, analysisType);
}

async function byHttp(content, analysisType){
    try {
        const https = require('https');

        const response = await new Promise((resolve, reject) => {
            //url="https://openrouter.ai/api/v1/chat/completions";
            const req = https.request("https://ark.cn-beijing.volces.com/api/v3/chat/completions", {
                method: "POST",
                headers: {
                    //换成你的token
                    "Authorization": "Bearer d0d32978-95f4-4128-bf25-961863e159da",
                    "Content-Type": "application/json"
                }
            }, (res) => {
                let data = '';
                res.on('data', (chunk) => {
                    data += chunk;
                });
                res.on('end', () => {
                    resolve({
                        ok: res.statusCode >= 200 && res.statusCode < 300,
                        status: res.statusCode,
                        json: () => Promise.resolve(JSON.parse(data))
                    });
                });
            });

            req.on('error', (error) => {
                reject(error);
            });

            req.write(JSON.stringify({
                "model": "deepseek-v3-241226",
                "messages": [
                    {
                        "role": "user",
                        "content": content
                    }
                ]
            }));
            req.end();
        });

        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }

        const data = await response.json();
        let content2 = data.choices[0].message.content;
        content2 = content2.startsWith("```json") ? content2.substring(7) : content2
        content2 = content2.endsWith("```") ? content2.substring(0, content2.length - 3) : content2
        return content2;

    } catch (error) {
        console.error('Error querying AI:', error);
        return null;
    }
}

async function byOpenAI(content, analysisType) {
    const openai = new OpenAI(
        {
            // 若没有配置环境变量，请用百炼API Key将下行替换为：apiKey: "sk-xxx",
            //换成你的token
            apiKey: 'd0d32978-95f4-4128-bf25-961863e159da',
            baseURL: "https://ark.cn-beijing.volces.com/api/v3/chat/completion"
        }
    );
    const completion = await openai.chat.completions.create({
        model: "deepseek-v3-241226",  // 此处以 deepseek-r1 为例，可按需更换模型名称。
        messages: [
            { role: "user", content: content }
        ],
    });
    let content2 = completion.choices[0].message.content;
    content2 = content2.startsWith("```json") ? content2.substring(7) : content2
    content2 = content2.endsWith("```") ? content2.substring(0, content2.length - 3) : content2
    return content2;
}

module.exports = queryAI;